package ru.nosport.matrixaria.modules.core.rmh;

import ru.nosport.matrixaria.core.MessageHandler;
import ru.nosport.matrixaria.core.MessageHandlerException;

import java.rmi.RemoteException;
import java.util.Map;

/**
 *
 * User: vfabr
 * Date: 25.10.2006
 * Time: 14:07:59
 *
 */
class RemoteMessageHandlerServer implements RMHServer {
	private final Map<Long, Object> buffer;

	/**
	 * Creates and exports a new object using random anonymous port
	 *
	 * @throws RemoteException if failed to export object 
	 */
	public RemoteMessageHandlerServer() throws RemoteException {
		this.buffer = new CircularFifoMap<Long, Object>();
	}

	@SuppressWarnings({"JavadocReference"})
	public Object rmhCall(int _senderId, int _requestId, String _name, String _method, Object[] _params) throws RemoteException, MessageHandlerException {
		Long hashKey = (long)_senderId * 95621 + (long)_requestId;
		if (!this.buffer.containsKey(hashKey)) {
			this.buffer.put(hashKey, this.rmhCall(_name, _method, _params));
		}
		return(this.buffer.get(hashKey));
	}
	/**
	 * Server routine wrapping MessageHandler.sendMessage for remote call.
	 *
	 * @param _name Object instance name
	 * @param _method Method name to be called
	 * @param _params Array of method parameters
	 * 			(<i>should be specified even if all parameters being passed are <u>null</u></i>)
	 *
	 * @return Result of method execution.
	 *
	 * @throws RemoteException if execution failure occured.
	 * @throws MessageHandlerException if target exception occured.
	 */
	public Object rmhCall(String _name, String _method, Object[] _params) throws RemoteException, MessageHandlerException {
		return MessageHandler.sendMessage(_name, _method, _params);
	}
}
